<?php
//模型
class MemberCardModel extends MY_Model {
	function __construct(){
		parent::__construct();
		$this->table = 'user_card';
	}
	function get_list($uid,$cid){
		
		$where = "uc.user_id ='{$uid}' AND uc.cid='{$cid}' ";
		
		
		$sql  = "select uc.id,uc.total_num,uc.num,uc.price,(select card_name from ".$this->db->dbprefix."course_card where id=uc.card_id ) as name from ".$this->db->dbprefix.$this->table." as uc LEFT JOIN ".$this->db->dbprefix."course AS c ON c.id = uc.cid where {$where} limit 100";

		$query = $this->db->query($sql);
		$res = $query->result_array();
		
		return $res;
	}
	function get_info($uid,$id){
		
		$where = " id='{$id}' AND user_id ='{$uid}' ";
		
		$sql  = "select id,total_num,num,price from ".$this->db->dbprefix.$this->table." where {$where} order by addtime desc limit 1";

		$query = $this->db->query($sql);
		$row = $query->row_array();
		
		return $row;
	}
	
	function course_get_uid($cids=array()){
		$ids = '';
		if(is_array($cids)){
			$ids = implode(',',$cids);
		}
		if(empty($ids)){
			return false;
		}
		
		$where = "cid in ({$ids})";

		$where .= " AND num>0";
		
		$sql  = "select * from ".$this->db->dbprefix.$this->table." where {$where} limit 100";

		$query = $this->db->query($sql);
		$res = $query->result_array();
		
		return $res;
	}
	/*
	function uid_get_info($uid){
		
		$where = " user_id ='{$uid}' ";
		
		$sql  = "select * from ".$this->db->dbprefix.$this->table." where {$where} limit 1";

		$query = $this->db->query($sql);
		$row = $query->row_array();
		
		return $row;
	}
	*/
	function reduce($uid,$card_id,$cnum=1){
		$row = $this->get_info($uid,$card_id);
		if(!$row){
			$this->addError('会员卡不存在');
			return false;
		}
		
		$num = $row['num'];
		if($num<=0){
			$this->addError('会员卡次数不足');
			return false;
		}
		$num -= $cnum;
		
		$sql = "UPDATE ".$this->db->dbprefix.$this->table." SET `num`='{$num}' WHERE  `user_id`='{$uid}' AND id='{$card_id}' limit 1";
		$query = $this->db->query($sql);
		return true;
	}
	function addto($uid,$card_id,$cnum=1){
		$row = $this->get_info($uid,$card_id);
		if(!$row){
			$this->addError('会员卡不存在');
			return false;
		}
		
		$num = $row['num'];

		$num += $cnum;
		
		$sql = "UPDATE ".$this->db->dbprefix.$this->table." SET `num`='{$num}' WHERE  `user_id`='{$uid}' AND id='{$card_id}' limit 1";
		$query = $this->db->query($sql);
		return true;
	}
}

